<template>
  <a-drawer
      :title="title"
      :visible="visible"
      :destroyOnClose="true"
      :width="800"
      :body-style="{ paddingBottom: '80px' }"
      @close="closeModal"
  >
    <a-form layout="vertical">
      <a-row :gutter="[16, 16]">
        <template v-if="isWorkAiOrg">
          <a-col :span="24">
            <a-form-item v-bind="validateInfos.name">
              <template #label>
                <span style="margin-right: 5px">配置名称</span>
                <a-tooltip>
                  <template #title
                  >请使用易区分的文本来命名
                  </template
                  >
                  <QuestionCircleOutlined/>
                </a-tooltip>
              </template>
              <a-input
                  v-model:value="modelRef.name"
                  placeholder="请输入配置名称"
              />
            </a-form-item>
          </a-col>
        </template>
        <template v-else>
          <a-col :span="12">
            <a-form-item v-bind="validateInfos.name">
              <template #label>
                <span style="margin-right: 5px">配置名称</span>
                <a-tooltip>
                  <template #title
                  >请使用易区分的文本来命名，<br/>例：某某大厦停车场
                  </template
                  >
                  <QuestionCircleOutlined/>
                </a-tooltip>
              </template>
              <a-input
                  v-model:value="modelRef.name"
                  placeholder="请输入配置名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12" v-show="!isWorkAiOrg">
            <a-form-item label="所属公司收支账户" v-bind="validateInfos.account_id"
                         style="position: relative">
              <a-cascader style="width: 100%" placeholder="选择所属公司收支账户"
                          v-model:value="modelRef.account_id" :options="companyList"
                          :load-data="getAccount"/>
              <a-button type="link" class="fast-add"
                        @click="addAccount">快速添加
              </a-button>
            </a-form-item>
          </a-col>
        </template>

        <a-col :span="12">
          <a-form-item label="支付方式" v-bind="validateInfos.pay_method">
            <a-select
                v-model:value="modelRef.pay_method"
                :options="optionsPayment"
                :disabled="optionsType"
            />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="支付通道" v-bind="validateInfos.pay_sdk">
            <a-select
                v-model:value="modelRef.pay_sdk"
                :options="optionsPaysdk"
                :disabled="optionsType"
            />
            <a-button v-if="modelRef.pay_sdk == 'allinpay'" @click="accountes" type="link"
                      style="padding-left: 25px;position: relative;">
              <img style="position: absolute; top: 7px; left: 7px; width: 16px;"
                   src="../../../../components/Collection/flame.png"/>
              快速创建收款账户 >
            </a-button>
          </a-form-item>
        </a-col>
      </a-row>
      <a-card title="支付配置" style="margin-bottom: 20px; width: 100%">
        <a-row :gutter="[16, 16]">
          <a-col :span="24">
            <a-form-item label="使用环境" v-bind="validateInfos.pay_env">
              <a-checkbox
                  v-model:checked="checkAll"
                  :indeterminate="indeterminate"
                  @change="onCheckAllChange"
              >全选
              </a-checkbox
              >
              <a-checkbox-group
                  @change="checkedListChange"
                  v-model:value="modelRef.pay_env"
                  :options="plainOptions"
                  :disabled="disabledType"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12" v-for="(domain, index) in domainsList" :key="index">
            <a-form-item>
              <template #label>
                <span style="margin-right: 5px">{{ domain.name }}</span>
                <a-tooltip>
                  <template #title>{{ domain.tip }}</template>
                  <QuestionCircleOutlined/>
                </a-tooltip>
              </template>
              <a-input
                  v-if="domain.type !== 'file'"
                  v-model:value="modelRef.pay_param[domain.value || domain.key]"
                  :placeholder="domain.placeholder"
              />
              <a-upload
                  v-else
                  :action="$utils.fileAction"
                  :headers="{ 'org-token': $store.getters.token }"
                  :multiple="false"
                  v-model:file-list="domain.urlList"
                  @change="(info) => uploadFile(info, domain.value || domain.key)"
                  name="file"
                  :data="{ dir: 'pay_cert' }"
                  accept=".pem"
              >
                <a-button>
                  <UploadOutlined/>
                  上传文件
                </a-button>
              </a-upload>
            </a-form-item>
          </a-col>
          <a-col :span="12" v-if="wechatIsShow">
            <a-form-item label="绑定过的公众号">
              <a-select
                  v-model:value="modelRef.pay_param.appid"
                  :options="optionsBindAccount"
                  placeholder="请选择"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-card>
    </a-form>
    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="closeModal">取消</a-button>
      <a-button type="primary" @click="onSubmit">保存</a-button>
    </div>

    <account
        v-if="Collection"
        :visible="Collection"
        :ApprovedOrNot="Approvedtype"
        @close="Collectionclose"
    />

    <account-add
        @cancel="addAccountClose"
        @success="addSuccess"
        :visible="addVisible"
        @request="$utils.commonRequest"
    ></account-add>


  </a-drawer>
</template>

<script>
import {
  computed,
  defineComponent,
  nextTick,
  reactive,
  ref,
  toRaw,
  toRefs,
  watch,
} from "vue";
import {Form, message, TreeSelect} from "ant-design-vue";

const useForm = Form.useForm;
import {QuestionCircleOutlined, UploadOutlined} from "@ant-design/icons-vue";
import utils from "../../../../common/utils/utils";
import request from "../../../../common/utils/request";
import store from "../../../../store/index";
import account from "../../../../components/Collection/account.vue"
import AccountAdd from '@/views/setting/UserAccount/modules/AccountAdd.vue'

export default defineComponent({
  name: "EditAccess",
  components: {AccountAdd, QuestionCircleOutlined, TreeSelect, UploadOutlined, account},
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    id: {
      type: [String, Number],
      default: 0,
    },
  },
  setup(props, context) {
    const state = reactive({
      villageData: [],
      optionsPayment: [],
      payMethodList: [],
      optionsPaysdk: [],
      checkAll: false,
      indeterminate: false,
      plainOptions: [],
      domainsList: [],
      optionsType: false,
      disabledType: false,
      optionsBindAccount: [],
      wechatIsShow: false,
      Approvedtype: false,
      Collection: false,
      companyList: [],
      addVisible: false,
      isSetDefault: false,

    });

    // 是否workAiOrg
    const isWorkAiOrg = computed(() => {
      if (
          store.getters.orgInfo &&
          store.getters.orgInfo.org_type &&
          store.getters.orgInfo.org_type == "workAi"
      ) {
        return true;
      } else {
        return false;
      }
    });

    const initKeys = [
      "name",
      "account_id",
      "pay_method",
      "pay_sdk",
      "pay_env",
      "pay_param",
    ];
    const modelRef = reactive({
      name: "",
      pay_method: undefined,
      pay_sdk: undefined,
      pay_env: [],
      pay_param: {
        appid: undefined,
      },
      account_id: undefined,
    });

    const required = [
      {
        required: true,
        message: "必填项",
      },
    ];
    const rulesRef = reactive({
      name: required,
      account_id: required,
      pay_method: required,
      pay_sdk: required,
      pay_env: required,
    });
    const {resetFields, validate, validateInfos} = useForm(
        modelRef,
        rulesRef
    );

    // 支付方式/通道列表
    const payMethodList = () => {
      request.get("/pay", "/org/pay/method_list").then((res) => {
        state.optionsPayment = res.payMethodList.map((item, index) => {
          if (!state.optionsType) {
            if (index == 0) {
              modelRef.pay_method = item.value;
              state.optionsPaysdk = item.methodList.map(
                  (paysdk, paysdkIndex) => {
                    if (paysdkIndex == 0) {
                      modelRef.pay_sdk = paysdk.value;
                      state.plainOptions = paysdk.env.map((payEnv) => {
                        return {
                          label: payEnv.name,
                          value: payEnv.value,
                        };
                      });
                      state.domainsList = paysdk.param;
                      state.domainsList.forEach((item) => {
                        if (item.type == "file") {
                          item.urlList = [];
                        }
                      });
                      for (let param of state.domainsList) {
                        modelRef.pay_param[param.value || param.key] = "";
                        rulesRef[param.value || param.key] = required;
                      }
                    }
                    return {
                      value: paysdk.value,
                      label: paysdk.name,
                      ...paysdk,
                    };
                  }
              );
            }
          }

          return {
            value: item.value,
            label: item.name,
            ...item,
          };
        });
      });
    };

    // 支付方式切换
    watch(
        () => modelRef.pay_method,
        (key) => {
          if (!state.optionsType) {
            state.disabledType = false;
            state.checkAll = false;
            state.indeterminate = false;
            modelRef.pay_env = [];
          }
          state.optionsPayment.forEach((item) => {
            if (item.value == key) {
              state.optionsPaysdk = item.methodList.map((paysdk, index) => {
                if (!state.optionsType) {
                  if (index == 0) {
                    modelRef.pay_sdk = paysdk.value;
                    state.plainOptions = paysdk.env.map((payEnv) => {
                      return {
                        label: payEnv.name,
                        value: payEnv.value,
                      };
                    });
                    state.domainsList = paysdk.param;
                  }
                }

                return {
                  value: paysdk.value,
                  label: paysdk.name,
                  ...paysdk,
                };
              });
            }
          });
          for (let key in modelRef) {
            if (!initKeys.includes(key)) {
              delete modelRef.pay_param[key];
              delete rulesRef[key];
            }
          }
          if (!state.optionsType) {
            for (let param of state.domainsList) {
              modelRef.pay_param[param.value || param.key] = "";
              rulesRef[param.value || param.key] = required;
            }
          }
        }
    );

    // 支付通道切换
    watch(
        () => modelRef.pay_sdk,
        (key) => {
          if (!state.optionsType) {
            state.disabledType = false;
            state.checkAll = false;
            state.indeterminate = false;
            modelRef.pay_env = [];
          }
          state.optionsPayment.forEach((item, index) => {
            if (modelRef.pay_method == item.value) {
              item.methodList.forEach((method) => {
                if (key == method.value) {
                  state.plainOptions = method.env.map((payEnv) => {
                    return {
                      label: payEnv.name,
                      value: payEnv.value,
                    };
                  });
                  state.domainsList = method.param;
                  state.domainsList.forEach((item) => {
                    if (item.type == "file") {
                      item.urlList = [];
                    }
                  });
                }
              });
            }
          });
          for (let key in modelRef) {
            if (!initKeys.includes(key)) {
              delete modelRef.pay_param[key];
              delete rulesRef[key];
            }
          }
          if (!state.optionsType) {
            for (let param of state.domainsList) {
              modelRef.pay_param[param.value || param.key] = "";
              rulesRef[param.value || param.key] = required;
            }
          }
        }
    );

    // 使用环境选择
    const onCheckAllChange = (e) => {
      if (!e.target.checked) {
        modelRef.pay_env = [];
        state.checkAll = false;
        state.indeterminate = false;
        state.disabledType = false;
        state.wechatIsShow = false;
        modelRef.pay_param.appid = undefined;
        return;
      }
      modelRef.pay_env = state.plainOptions.map((item) => item.value);
      if (modelRef.pay_env.includes("wechatH5")) {
        state.wechatIsShow = true;
      }
    };
    watch(
        () => modelRef.pay_env,
        (val) => {
          if (!val.length) {
            state.disabledType = false;
            state.checkAll = false;
            state.indeterminate = false;
            state.wechatIsShow = false;
            modelRef.pay_param.appid = undefined;
            return;
          }
          if (val.includes("wechatH5")) {
            state.wechatIsShow = true;
          }
          if (val.length == state.plainOptions.length) {
            state.disabledType = true;
            state.checkAll = true;
            state.indeterminate = false;
          } else {
            state.disabledType = false;
            state.checkAll = false;
            state.indeterminate = true;
          }
        }
    );
    const checkedListChange = (e) => {
      if (e.includes("wechatH5")) {
        state.wechatIsShow = true;
      } else {
        state.wechatIsShow = false;
        modelRef.pay_param.appid = undefined;
      }
      if (e.length == 0) {
        state.checkAll = false;
        state.indeterminate = false;
        state.disabledType = false;
        state.indeterminate = true;
        return;
      }
      if (e.length == state.plainOptions.length) {
        state.checkAll = true;
        state.indeterminate = false;
        state.disabledType = true;
      } else {
        state.checkAll = false;
        state.indeterminate = true;
        state.disabledType = false;
      }
    };

    // 微信公众号
    const wechatList = () => {
      request.get("/third", "/org/wechat_list").then((res) => {
        state.optionsBindAccount = res.list.map((item, index) => {
          return {
            value: item.wechat_appid,
            label: item.wechat_name,
          };
        });
      });
    };

    const title = computed(() => {
      return props.id ? "编辑支付配置" : "新增支付配置";
    });

    // 关闭弹窗
    const closeModal = () => {
      context.emit("clear");
      resetFields();
    };

    const onSubmit = () => {
      validate().then(() => {
        // let param = {};
        // param = { ...modelRef };
        // let object = {};
        // state.domainsList.map((item) => {
        //   object[item.value || item.key] = item.text;
        // });
        // param.pay_param = object;
        const params = {
          ...modelRef
        }
        if (modelRef.account_id) {
          params.company_id = modelRef.account_id[0]
          params.account_id = modelRef.account_id[1]
        }
        if (props.id) {
          request.put("/pay", "/org/pay/config", params).then((res) => {
            message.success("修改成功");
            context.emit("submitBtn");
            resetFields();
          });
          return;
        }
        request.post("/pay", "/org/pay/config", params).then((res) => {
          message.success("添加成功");
          context.emit("submitBtn");
          resetFields();
        });
      });
    };

    const toGetAccount = (company_id) => {
      if (state.companyList.length) {
        state.companyList.forEach(item => {
          if (item.value == company_id) {
            getAccount([item])
          }
        })
      } else {
        setTimeout(() => {
          toGetAccount(company_id);
        }, 1000);
      }
    }

    const configDetail = () => {
      request
          .get("/pay", "/org/pay/config/detail", {id: props.id})
          .then((res) => {
            let detail = res.detail;
            setModelRef(detail);
            modelRef.pay_sdk = detail.pay_sdk;
            modelRef.pay_env = detail.pay_env;
            if (detail?.company_id && detail?.account_id) {
              modelRef.account_id = [detail.company_id, detail.account_id];
              toGetAccount(detail.company_id);
            }
            if (!detail.company_id || !detail.account_id) {
              setDefaultFirst()
            }

            console.log(modelRef.account_id)
            nextTick(() => {
              state.domainsList.forEach((item) => {
                if (item.type == "file") {
                  if (item.value == "cert_path") {
                    item.urlList = detail.pay_param.cert_path
                        ? [
                          {
                            uid: 0,
                            name: detail.pay_param.cert_path,
                            status: "done",
                            url: detail.pay_param.cert_path,
                          },
                        ]
                        : [];
                  }
                  if (item.value == "key_path") {
                    item.urlList = detail.pay_param.key_path
                        ? [
                          {
                            uid: 0,
                            name: detail.pay_param.key_path,
                            status: "done",
                            url: detail.pay_param.key_path,
                          },
                        ]
                        : [];
                  }
                }
              });
            });
            // setTimeout(() => {
            //   if (state.domainsList.length) {
            //     let paramList = convertToArray(detail.pay_param);
            //     if (paramList.length) {
            //       state.domainsList.forEach((item) => {
            //         paramList.forEach((param) => {
            //           if (item.key == param.value) {
            //             item.text = param.text;
            //           }
            //         });
            //       });
            //     }
            //   }
            // }, 100);
            // state.domainsList=convertToArray(detail.pay_param)
          });
    };
    const setModelRef = (state) => {
      for (let key in state) {
        modelRef[key] = state[key];
      }
    };

    const convertToArray = (objct) => {
      return Object.keys(objct).map((key) => ({
        value: key,
        text: objct[key],
      }));
    };

    const uploadFile = (info, data) => {
      let resFileList = [...info.fileList];
      modelRef.pay_param[data] = [];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
        modelRef.pay_param[data] = resFileList[0].url;
      } else {
        modelRef.pay_param[data] = "";
      }
    };

    const accountes = () => {
      request
          .get("/pay", "/incoming/info", {
            org_id: store.getters.userInfo.org_id,
            status: -1,
          }).then((res) => {
        if (res.list.length == 0) {
          state.Approvedtype = false
        } else {
          state.Approvedtype = true
        }
        state.Collection = true
      })
    }

    const Collectionclose = () => {
      state.Collection = false
    }

    const setDefaultFirst = () => {
      state.isSetDefault = true;
      if (state.companyList.length) {
        const companyId = state.companyList[0].value
        modelRef.account_id = [companyId]
        toGetAccount(companyId)
      }
    }

    const getCompanyList = () => {
      request.get("/org", "/company/orgAndBranch").then(res => {
        console.log(res)
        state.companyList = res.list.map(item => {
          return {
            label: item.company,
            value: item.id,
            isLeaf: false
          }
        })
        if (!props.id) {
          setDefaultFirst();
        }

      })
    }


    const getAccount = (selectedOptions) => {
      const targetOption = selectedOptions[selectedOptions.length - 1];
      targetOption.loading = true;
      request
          .get("/org", "/manage/account", {
            page: 1,
            pageSize: 9999,
            org_branch_id: targetOption.value,
          })
          .then((res) => {
            if (res.list) {
              targetOption.loading = false;
              targetOption.children = res.list.map((item) => ({
                label: item.name,
                value: item.id,
                isLeaf: true,
              }));
              state.companyList = [...state.companyList];
              if (modelRef.account_id.length == 2) {
                //之前配置的被删除了
                const accountArr = res.list.filter(item => {
                  return item.id == modelRef.account_id[1]
                })
                if (accountArr.length == 0) {
                  if (state.companyList.length > 0 && res.list.length > 0) {
                    modelRef.account_id = [state.companyList[0].value, res.list[0].id]
                  }
                }
              }

              if (state.isSetDefault && res.list?.length > 0) {
                const cid = modelRef.account_id[0]
                console.log(modelRef.account_id)
                modelRef.account_id = [cid, res.list[0].id]
              }
            }
          });
    };

    const init = () => {
      payMethodList();
      wechatList();
      getCompanyList();
    };

    watch(
        () => props.visible,
        (val) => {
          if (val) {
            init();
            if (props.id) {
              configDetail();
              state.optionsType = true;
            } else {
              state.optionsType = false;
            }
          } else {
            state.companyList = []
          }
        }
    );

    const addAccount = () => {
      state.addVisible = true;
    }

    const addSuccess = () => {
      addAccountClose();
      if (modelRef.account_id) {
        toGetAccount(modelRef.account_id[0])
      }
    };

    const addAccountClose = () => {
      state.addVisible = false;
    };


    return {
      closeModal,
      title,
      validateInfos,
      resetFields,
      onSubmit,
      modelRef,
      ...toRefs(state),
      onCheckAllChange,
      checkedListChange,
      uploadFile,
      accountes,
      Collectionclose,
      isWorkAiOrg,
      getAccount,
      addAccount,
      addSuccess,
      addAccountClose,

    };
  },
});
</script>

<style lang="less" scoped>

.fast-add {
  font-size: 12px;
  position: absolute;
  padding-right: 0;
  padding-left: 12px;
  top: -33px;
  right: -5px;
}
</style>
